package edu.cuit.canary.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关认证全局过滤器：
 *  全局过滤器作用于所有路由：需要用户登录(认证)才能路由
 */
@Order(1)
@Component
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.通过上下文获取请求对象
        var request = exchange.getRequest();
        //2.获取认证请求头 authorization
        var token = request.getHeaders().getFirst("Authorization");
        if(!StringUtils.hasLength(token)){
            //设置响应状态为未认证
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete(); //不放行给执行链上的下个执行对象(拦截:响应完成)
        }
        //解析token:判断是否为有效登录用户(自己完成)
        return chain.filter(exchange); //将请求放行给执行链上的下一个执行对象
    }
}
